package server_commands;

import static server.RLM_Server.activeConnections;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

/**
 * Potklasa klase Command koja reprezentuje komandu za procesuiranje promene
 * statusa.
 * 
 * @author Uros Krikic & Martin Jondzic
 *
 */
public class CHSTATUSCommand extends Command {

	
	public CHSTATUSCommand(String parameter) {
		setCode(CHSTATUS_CMD);
		setParameter(parameter);
	}
	
	/**
	 * Vrsi se promena statusa korisnika u trazeni i obavestavaju se svi korisnici,
	 * na cijoj je listi aktuelni korisnik, o novom statusu.
	 * 
	 * @param connection - konekcija ka klijentu
	 * @param dbConnection - objekat za rad sa bazom
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		StringTokenizer tokenizer = new StringTokenizer(getParameter());
		
		String username = tokenizer.nextToken();
		String newStatus = tokenizer.nextToken();
		String nickname = tokenizer.nextToken();
		String email = tokenizer.nextToken();
		String avatar = tokenizer.nextToken();
		
		try {
			dbConnection.doUpdateStatement("UPDATE tblUsers SET tblUsers.status = '" +
					newStatus + "' WHERE tblUsers.username = '" + username + "'");
		
		
		
			connection.setMessage("100 Status OK");
			
			String SQLSelectQuery = "SELECT tblContacts.user_dest " +
			"FROM tblContacts " +
			"WHERE  tblContacts.user_source = '" + username + "' AND tblContacts.user_dest NOT IN " +
			"(SELECT tblBlocks.user_dest FROM tblBlocks WHERE tblBlocks.user_source = '" + username + "');";	
	
			dbConnection.doStatement(SQLSelectQuery);			
	
			ArrayList array = (ArrayList)dbConnection.data.clone();
	
			
			if(array.size() == 0) {
				dbConnection.doCommit();
				return true;
			}
			
			String message = "SERV_CHSTATUS " + username + " " + newStatus + " " + nickname +
										  " " + email + " " + avatar;
			
			// Obavestava sve korisnike o logovanju aktuelnog korisnika
		
			Iterator usersIterator = array.iterator();
			
			while ( usersIterator.hasNext() ) {
				
				// username korisnika 
				String user = ((Vector)usersIterator.next()).get(0).toString();
				
				ServerSocketConnection tempConnection = activeConnections.get(user);
				
				if (tempConnection != null) {
					tempConnection.setMessage(message);
//					System.out.println("Korisnik koji se obavestava o promeni statusa novog usera: " + user);
				}
			}
			
			System.out.println("--> User " + username + " has just changed the status!");
		
		} catch (SQLException e) {
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}

}
